/*****目标团队*****/
<template><!---->
  <search-table
  :columns="targetTeamCol" :data="targetTeamData"
      :total=	targetTeamTotal
            @change-page="getTargetPage"
            @change-size="getTargetSize"
            :page.sync="queryTargetTeamInfo.pageIndex"
            :size.sync="queryTargetTeamInfo.pageSize">
            <template slot="search">
              <Button  type='primary'  ghost @click="showAddAndUpdate('')" :disabled="disabledAllBtn"><Icon type="ios-add" :size="16"/> 添加题目</Button>
            </template>
  <Modal v-model="targetModal.show"
  :title="targetModal.title"
  :loading = "targetModal.loading"
  width="600px"
  :mask-closable = "false"
  @on-cancel="handleReset('formValidate')"
  @on-ok="saveTargetTeam">
  <Form  ref="formValidate"  :model="formValidate"  :rules="ruleValidate" :label-width="80" >
    <FormItem  label="靶标类型" prop="type" v-if="type==0&&(hlConfig==2)" >
      <RadioGroup v-model="formValidate.type" @on-change="changeType()">
        <Radio :label=0 :disabled="targetModal.type != 1">私有</Radio>
        <Radio :label=2 :disabled="targetModal.type != 1">公共</Radio>
        <Radio :label=3 :disabled="targetModal.type != 1">隐藏</Radio>
      </RadioGroup>
      <span style="color:#f90"> <Icon type="ios-information-circle-outline" />公共靶标和隐藏靶标不可分配团队</span>
    </FormItem>

    <FormItem label="所属团队"  prop="teamId" v-if="[1,2,3,4,5,6,7,8,9].includes(type)||(type==0&&hlConfig==0)||(type==0&&hlConfig==2&&formValidate.type==0)" key="teamId" :rules="ruleValidate.teamId">
      <Select filterable  v-model="formValidate.teamId" clearable placeholder="请选择团队" @on-change="changeTeamGroup" filterable :disabled="targetModal.type === 2">
        <Option  v-for="item in accessGroupList" :value="item.id"  :key="item.id" :title="item.name">{{item.name}}</Option>
      </Select>
    </FormItem>
   <FormItem label="所属团队"  prop="teamId1"  v-else-if="(type==0&&hlConfig==1)" key="teamId1" :rules="ruleValidate.teamId1">
      <Select filterable  v-model="formValidate.teamId" clearable placeholder="请选择团队" @on-change="changeTeamGroup" filterable :disabled="targetModal.type === 2">
        <Option  v-for="item in accessGroupList" :value="item.id"  :key="item.id" :title="item.name">{{item.name}}</Option>
      </Select>
    </FormItem>
    <!-- <FormItem label="所属团队"   v-else>
      <Select filterable  v-model="formValidate.teamId" placeholder="请选择团队" @on-change="changeTeamGroup" filterable :disabled="targetModal.type === 2">
        <Option  v-for="item in accessGroupList" :value="item.id"  :key="item.id" :title="item.name">{{item.name}}</Option>
      </Select>
    </FormItem> -->
    <FormItem label="虚拟机" prop="vmId" key="vmId">
      <Select filterable v-model="formValidate.vmId" placeholder="请选择虚拟机" filterable  @on-change="changeVm"  :disabled="targetModal.type === 2">
        <Option v-for="item in vmlists" :value="item.id" :key="item.id" :title="item.name" :disabled="usedVmList.includes(item.id)">{{item.name}}</Option>
      </Select>
    </FormItem>
    <FormItem  label="题目显示名称" prop="name" key="name">
      <Input v-model.trim="formValidate.name" placeholder="题目显示名称"></Input>
    </FormItem>
    <FormItem  label="描述" prop="description" key="description">
      <Input type="textarea" :maxlength="200" v-model.trim="formValidate.description" placeholder="描述"></Input>
    </FormItem>
    <FormItem label="分值" prop="score" v-if="hlConfig!=2" key="score">
      <InputNumber :min="1" :max="1000" v-model="formValidate.score" placeholder="请输入分值"></InputNumber><span style="color:#f90" v-if="type != 4"> <Icon type="ios-information-circle-outline" />此分值为该靶标被攻破时，攻击团队的加分或成功防守的得分</span>
    </FormItem>
    <FormItem  label="是否显示" prop="visibility" v-if="hlConfig!=2" key="visibility">
      <RadioGroup v-model="formValidate.visibility">
        <Radio :label=1  >显示</Radio>
        <Radio :label=0 >不显示</Radio>
      </RadioGroup>
      <span style="color:#f90"> <Icon type="ios-information-circle-outline" />用于在演练页面的展示控制</span>
    </FormItem>
    <FormItem  label="Flag路径" key="path" >
       <!-- v-if="formValidate.type == 0" -->
      <Input v-model.trim="path" placeholder="请输入路径" ></Input>
    </FormItem>
    <!--渗透需要题目顺序-->
    <FormItem  label="排序" prop="sequence" v-if="type == 4">
      <InputNumber v-model="formValidate.sequence" :min="1" placeholder="请输入排序"></InputNumber>
    </FormItem>

    <FormItem  label="访问方式" prop="access" v-if="hlConfig!=2">
      <RadioGroup v-model="access" @on-change="changeAccess">
        <Radio label="1">内网访问</Radio>
        <Radio label="2">映射访问</Radio>
      </RadioGroup>
    </FormItem>
    <FormItem  :label="hlConfig==2 ? '访问端口' : '端口'" prop="port" v-if="access == '1'||hlConfig==2" key="port">
      <Input v-model.trim="formValidate.port" placeholder="请输入PORT(1~65535)" style="width:300px"  ></Input>
    </FormItem>
    <FormItem  :label="hlConfig==2 ? '访问IP' : '外网IP'"  prop="externalIp" v-if="access == '2'||hlConfig==2"  key="externalIp">
      <Input v-model.trim="formValidate.externalIp" placeholder="请输入IP"></Input>
    </FormItem>
    <FormItem  label="外网端口" prop="externalPort" v-if="access == '2'&&hlConfig!=2" key="externalPort">
      <Input v-model.trim="formValidate.externalPort" placeholder="请输入PORT(1~65535)" style="width:300px" ></Input>
    </FormItem>
    <FormItem  label="用户名" prop="user" v-if="hlConfig==2&&formValidate.type==0"  key="user">
      <Input v-model.trim="formValidate.user" placeholder="请输入用户名"></Input>
    </FormItem>
    <FormItem  label="密码" prop="password" v-if="hlConfig==2&&formValidate.type==0" key="password">
      <Input v-model.trim="formValidate.password" placeholder="请输入密码" style="width:300px" ></Input>
    </FormItem>
    <FormItem  label="连接IP" prop="ip" v-if="hlConfig==2&&formValidate.type==0" key="ip">
      <Input v-model.trim="formValidate.ip" placeholder="请输入IP" style="width:300px" ></Input>
    </FormItem>
  </Form>
</Modal>
  </search-table>
</template>

<script>
  import tableToopTip from '@/view/drill_compete/page/tableTooltip'
  import {getTargetTeamList,addTargetTeam,modifyTargetTeam,getTargetTeamInfo,delTargetTeam,queryVmWithParty,queryDeployedVms,getvmInfo} from '@/api/drill_compete'
  import {queryCtfList,getQuestionDetail} from '@/api/question'
  import {getFlagServerList,queryTargetList} from '@/api/drill'
  import {getaccessgrouplist} from '@/api/access_new'
  export default {
    name: 'scenes',
    props:['type','disabledAllBtn','step','hlConfig'],
    components:{tableToopTip},
  data(){
    const validateNum = (rule, value, callback) => { //验证只能填入数字
          var reg = new RegExp("^([1-9]|[1-9]\\d|100)$");
          //验证警戒值
          if(value){
            if (!reg.test(value)) {
              callback(new Error('请输入1-100的整数'));
            }else{
              callback()
            }
          }else{
            callback()
          }
        }
    const validateScore = (rule, value, callback) => { //验证只能填入数字
          var reg = new RegExp("^(?!0)(?:[0-9]{1,3}|1000)$");
          //验证警戒值
          if(value || value === 0){
            if (!reg.test(value)) {
              callback(new Error('请输入1-1000的整数'));
            }else{
              callback()
            }
          }else{
            callback()
          }
        }
      const validatePort = (rule, value, callback) => { //验证只能填入数字
          var reg = new RegExp("^(([1-9]\\d{0,3})|([1-5]\\d{4})|(6[0-4]\\d{3})|(65[0-4]\\d{2})|(655[0-2]\\d)|(6553[0-5]))$");
          //验证警戒值
          if(value){
            if (!reg.test(Number(value))) {
              callback(new Error('请输入1-65535的整数'));
            }else{
              callback()
            }
          }else{
            callback()
          }
        }
        const validateIP = (rule, value, callback) => { //验证只能填入数字
          var reg = new RegExp("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
          //验证警戒值
          if(value){
            if (!reg.test(value)) {
              callback(new Error('ip格式错误'));
            }else{
              callback()
            }
          }else{
            callback()
          }
        }
      return {
        targettype:0,
        usedVmList: [],
        routeParams:{
          id:this.$route.query.id,
          prjid:this.$route.query.prjid
        },
        targetModal:{
          show:false,
          title:'',
          loading:true,
          type:1 //1添加，2修改
        },
        pathList:[],
//      isSaveDisabled:false,
//      showDisbaled:false,
//      isDisabled:false,
//      ishowTeam:true,
//      sencenMode:'',
//      sencenType:1,
//      selSenceName:'',
//      sencenList:[],
//      selSencenC:'',
//      sencenListC:[],
//      selSencen:'',
//      selSencenPrjId:'',
//      selSencenPrjIdC:'',
//      selSenceNameC:'',
//      searchPrjString: '',
//      PZ:10,
//      currentPage:1,
//      showFooter:true,
//      addSecens:false,
//      titleObj:{},
    accessGroupList:[],
        vmlists:[],
        teamlists:[],
    queryTargetTeamInfo:{
      pageIndex:1,
      pageSize:10,
      sceneId:this.$route.query.id,
      projectId:this.$route.query.prjid
    },
        questionList:[],
        access:'1',
        path:'',
        formValidate: {
          //"createTime": "2020-02-10T03:35:50.081Z",
      //"creator": "string",
      "description": "", //描述
      "externalIp": "", //对外ip
      "externalPort": "", //对外端口
      //"ip": "string",
      "name": "", //题目显示名称
      "password": "",
      "user": "",
      "port": "",
      "ip": "",
      "projectId": this.$route.query.prjid,
      "questionId": '', //题目id
      "sceneId": this.$route.query.id,
      "score": 1,
      //"status": 0, //状态：1 正常/防护成功，2 被攻破，3 服务异常，4 被攻破+服务异常
      "teamId": "",
      "teamName": "",
      "type":0, //0 普通靶标 2公共靶标 3隐藏靶标
      // "type": 0, //靶标类型：0.单个虚拟机、1.多个虚拟机flag相同、2.多个虚拟机flag不同、3.文件类型
      //"user": "string",
      "visibility": 0, //可见性：是否可见- 0.不可见 1可见
      "vmId": "",
      "path":"",
      "sequence":1,
      //"access":'1'
        },
        oldFormValidate:{},
        ruleValidate: {
          name: [
            { required: true, message: '名字不能为空', trigger: 'change' }
          ],
          password: [
            { required: true, message: '密码不能为空', trigger: 'change' }
          ],
          user: [
            { required: true, message: '用户名不能为空', trigger: 'change' }
          ],
          IP: [
            { required: true,validator: validateIP, trigger: 'change' }
          ],
          description: [
            { required: true, message: '请输入描述信息', trigger: 'change' }
          ],
          type: [
            { required: true,type:'number',message: '请选择靶标类型', trigger: 'change' },
          ],
          score:[
            { required: true, type:'number',message: '请输入分值', trigger: 'change'},
            { validator: validateScore,trigger: 'change' }
          ],
          sequence:[
            { required: true, type:'number',message: '请输入排序', trigger: 'change'},
            { validator: validateNum, trigger: 'change' }
          ],
      path: [
            { required: true, message: '请输入路径', trigger: 'change' }
          ],
          port: [
            { validator: validatePort, trigger: 'change' }
                // {
                //     required: true, validator: (rule, value, callback) => {
                //         if (!value) {
                //             callback(new Error('请输入访问端口'))
                //         } else {
                //             if (!(/([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{4}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])/.test(value))) {
                //                 callback(new Error('请输入正确的访问端口'))
                //             } else {
                //                 callback()
                //             }
                //         }
                //     },
                //     trigger: 'change'
                // }
            ],
          externalPort:[
            { validator: validatePort, trigger: 'change' }
          ],
          externalIp: [
                {
                    required: true, validator: (rule, value, callback) => {
                        if (!value) {
                            callback(new Error('请输入访问IP'))
                        } else {
                            if (!(/^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/.test(value))) {
                                callback(new Error('请输入正确的访问IP'))
                            } else {
                                callback()
                            }
                        }
                    },
                    trigger: 'blur'
                }
            ],
            ip: [
                {
                    required: true, validator: (rule, value, callback) => {
                        if (!value) {
                            callback(new Error('请输入连接IP'))
                        } else {
                            if (!(/^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/.test(value))) {
                                callback(new Error('请输入正确的连接IP'))
                            } else {
                                callback()
                            }
                        }
                    },
                    trigger: 'blur'
                }
            ],

          questionId:[
            { required: true, message: '请选择题目', trigger: 'change'}
          ],
          visibility:[
            { required: true, type:'number',message: '请选择', trigger: 'change'}
          ],
          vmId:[
            { required: true, message: '请选择虚拟机', trigger: 'change'}
          ],
          teamId:[
            { required: true, message: '请选择团队', trigger: 'change'}
          ],
          teamId1:[
            { }
          ],
        },
        initTargetObjData:{
          "createtime": "",
          "createuser": localStorage.getItem('username'),
          "frequency": 0,
          "id": "",
          "isshow": 1,
          "lastupdatetime": "",
          "modifier": "",
          "sceneid": "",
          "targetdes": "",
          "targetname": "",
          "targetsubmittype":0,
          "targettype": 0,
          "teamid": "",
          "type": 0,
          "uri": "",
          "vmid": "",
          "score":'1'
        },
        querytime:{},
        targetTeamCol:[
//        {
//          type: 'index',
//          align: 'center',
//          ellipsis:true,
////          width:60
//        },
          {
            title:'题目显示名称',
            key:'name',
            align:'center',
            ellipsis:true,
            tooltip:true,
            placement:'top-left',
            width:300
          },
          {
            title:'虚拟机名称',
            key:'vmName',
            align:'center',
            ellipsis:true,
            tooltip:true,
            width:150
          },
          {
            title:'靶标类型',
            key:'type',
            align:'center',
            placement:'top-left',
            render:(h, params) => {
              return h('span',this.typeFilter(params.row.type))
            }
          },
          {
            title:'团队名称',
            key:'teamName',
            align:'center',
            ellipsis:true,
            tooltip:true,
            width:100
          },

//        {
//          title:'验证码类型',
//          key:'targetsubmittype',
//          align:'center',
//          width:140,
//          render:(h, params) => {
//            return h('span',this.targetSubmitTypeFilter(params.row.targetsubmittype))
//          }
//        },
//        {
//          title:'虚拟机名称',
//          key:'vmname',
//          align:'center',
//          ellipsis:true,
//          tooltip:true,
//        },
          {
            title:this.hlConfig==2?'访问IP':'外网IP',
            key:'externalIp',
            align:'center',
            ellipsis:true,
            tooltip:true,
            width:200,
          },

          {
            title:this.hlConfig==2?'访问端口':'内网端口',
            key:'port',
            align:'center',
            ellipsis:true,
            tooltip:true,
            width:100
          },
          {
            title:this.hlConfig==2?'连接IP':'内网IP' ,
            key:'ip',
            align:'center',
            ellipsis:true,
            tooltip:true,
            width:200
          },
         
          {
            title:'描述',
            key:'description',
            align:'center',
            ellipsis:true,
            width:200,
            tooltip:true,
          },

          {
            title:'路径',
            key:'path',
            align:'center',
//          tooltip:true,
            render:(h,params) => {
              if(params.row.targetTempInfos.length > 0){
                  return h(tableToopTip,{
                    props:{
                      content:params.row.targetTempInfos[0].info,
                      width:300,
                      placement:'top',
                      triggle:'hover'
                    }
                  })
              }else{
                return h('span','无')
              }

            }
          },
          {
            title:'外网端口',
            key:'externalPort',
            align:'center',
            ellipsis:true,
            tooltip:true,
            width:50,
          },
          {
            title:'是否显示',
            key:'visibility',
            align:'center',
            ellipsis:true,
            tooltip:true,
            placement:'top-right',
            render:(h,params) => {
        return h('Tag',{
          props:{
            color:params.row.visibility == 1 ? 'var(--status-yes)': 'var(--status-no)',
            type:"border"
          },
          on:{
                      click:()=>{
                        //this.showAddAndUpdate(params.row)
                      }
                  }
        },params.row.visibility == 1 ? '是' : '否' )
      }
          },
          {
            title:'分值',
            key:'score',
            align:'center',
            ellipsis:true,
            placement:'top-right',
            tooltip:true,
            render:(h,params) => {
        return h('Tag',{
          props:{
            color:'blue'
          }
        },params.row.score)
      }
          }, 
          {
            title:'用户名',
            key:'user',
            align:'center',
            ellipsis:true,
            width:150,
            tooltip:true,
          },
          {
            title:'密码',
            key:'password',
            align:'center',
            ellipsis:true,
            width:150,
            tooltip:true,
          },
          {
            title:'操作',
            key:'action',
//          align:'center',
            ellipsis:true,
            width:160,
            placement:'top-right',
            opList:[
                {
                    txt:'修改',
                    type:'modify',
                    disabled:() => {
                      return this.disabledAllBtn
                    },
                    fun:this.showAddAndUpdate
                },
                {
                    txt:'删除',
                    type:'delete',
                    tooltip:true,
                    disabled:() => {
                      return this.disabledAllBtn
                    },
                    fun:(data) => {
                        this.delTargetTeam(data.id)
                    },
                    title: '你确定要删除吗?'
                }
            ],
//             render:(h,params)=>{
//               return h('div',[
//                 h('Button',{
//                   props:{
//                     type:'text',
//                     size:'small',
//                     disabled:this.disabledAllBtn
//                   },
//                   attrs:{
//                     title:'修改'
//                   },
//                   style:{
// //                  marginRight:'5px'
//           border:'none',
//           background:'none',
//           boxShadow:'none'
//                   },
//                   on:{
//                     click:()=>{
//                       this.showAddAndUpdate(params.row)
//                     }
//                   }
//                 },[
//                   h('img', {
//                         attrs: {
// //                          src: !this.setReBtnStatus(params.row) ? require('../../../assets/globalIcon/modify.png'):require('../../../assets/globalIcon/dis-modify2.png'),
//                           src:this.disabledAllBtn ? require('../../../assets/project/modifys.png') : require('../../../assets/project/modifys-h.png')
//                         },
//                         style: {
//                             cursor: 'pointer',
// //			                'margin-right':'5px',
//                             'vertical-align': 'middle',
// //			                width:'16px',
// //			                height:'auto',
//                             display:'inline-block',
//                             marginBottom:'4px',
//                         },
//                     }),
// //                  h('span',{
// //                      style: {
// //                          cursor: 'pointer',
// ////                          color:!this.setReBtnStatus(params.row) ? '#2d8cf0' : '#c5c8ce'
// //							color:'#2d8cf0'
// //                      },
// //                  },'修改')
//                 ]),
//                 h('Poptip', {
//                   props: {
//                     confirm: true,
//                     'ok-text': "确定",
//                     'cancel-text': "取消",
//                     type: 'error',
//                     size: 'large',
//                     title: '你确定要删除吗?',
//                     transfer:true
//                   },
//                   on: {
//                     'on-ok': () => {
//                       this.delTargetTeam(params.row.id)
//                     }
//                   }
//                 }, [
//                   h('Button', {
//                     props: {
//                       type: 'text',
//                       size: 'small',
//                       disabled:this.disabledAllBtn
//                     },
//                     attrs:{
//                       title:'删除'
//                     },
//                     style: {
//                         border:'none',
//             background:'none',
//             boxShadow:'none'
//                     },
//                   }, [
//                     h('img', {
//                         attrs: {
// //                          src: !this.setReBtnStatus(params.row) ?require('../../../assets/globalIcon/del.png'):require('../../../assets/globalIcon/dis-del.png'),
//                           src:this.disabledAllBtn ? require('../../../assets/project/delNote-d.png') : require('../../../assets/project/delNote-h.png')
//                         },
//                         style: {
//                             cursor: 'pointer',
// //				                            'margin-right':'5px',
//                             'vertical-align': 'middle',
// //				                            width:'16px',
// //				                            height:'auto',
//                             display:'inline-block',
//                             marginBottom:'4px',
//                         },
//                     }),
// //                  h('span',{
// //                      style: {
// //                          cursor: 'pointer',
// ////                          color:!this.setReBtnStatus(params.row) ? '#2d8cf0' : '#c5c8ce'
// //							color:'#2d8cf0'
// //                      },
// //                  },'删除')
//                   ])
//                 ])
//               ])
//             }

          }
        ],
        targetTeamData:[],
        targetTeamTotal:0,
        TargetId:''
      }
  },
  filters:{

  },
  mounted(){
      //this.getAllSence()
      //this.getAllTargetHost();
      this.getAccessGroupList();
      //this.getAllVmlist();
      //this.queryCtfQuestionList();
      this.getTargetTeamList();
      if(this.type == 1){
        this.targetTeamCol.splice(2, 0, {
          title:'题目名称',
              key:'questionName',
              align:'center',
              ellipsis:true,
              tooltip:true,
        });
      }
      if(this.hlConfig == 2){
        this.targetTeamCol.splice(9,3);
      } else{
        this.targetTeamCol.splice(2,1);
        this.targetTeamCol.splice(11,2);
      }
    },
  watch: {
    path(val) {
      this.$set(this.formValidate, 'path', val)
    }
  },
    methods:{
      initData(){
        this.path = '';
        this.formValidate = {
            //"createTime": "2020-02-10T03:35:50.081Z",
        //"creator": "string",
        "description": "", //描述
        "externalIp": "", //对外ip
        "externalPort": "", //对外端口
        //"ip": "string",
        "name": "", //题目显示名称
        //"password": "string",
        "password": "",
        "user": "",
        "port": "",
        "ip": "",
        "projectId": this.$route.query.prjid,
        "questionId": '', //题目id
        "sceneId": this.$route.query.id,
        "score": 1,
        //"status": 0, //状态：1 正常/防护成功，2 被攻破，3 服务异常，4 被攻破+服务异常
        "teamId": "",
        "teamName": "",
        "type":0, //0 普通靶标 2公共靶标 3隐藏靶标
        // "type": 0, //靶标类型：0.单个虚拟机、1.多个虚拟机flag相同、2.多个虚拟机flag不同、3.文件类型           对抗演练 hlconfig为2新增type字段 旧type未被使用 屏蔽
        //"user": "string",
        "visibility": 0, //可见性：是否可见- 0.不可见 1可见
        "vmId": "",
        "path":"",
        "sequence":1,
        //"access":'1'
          }
      },
        // getSystemType(vmId){          // 对抗演练 hlconfig为2新增type字段 旧type未被使用 屏蔽
        //   return getvmInfo(vmId).then(res=>{
        //     if(res.code===1){
        //       const result = res.data.sysType;
        //       // let arr = Object.values(result);
        //       return result
        //     }
        //   })
        // },
      async showAddAndUpdate(info) {
       this.getAllVmlist()
          this.initData();
          this.targetModal.show = true;
          if (!info) {
            this.targetModal.title = '添加题目';
            this.targetModal.type = 1;
            this.access = "1";
          } else {
            this.targetModal.title = '修改题目';
            this.targetModal.type = 2;
            //this.formValidate = {};
//  			this.oldFormValidate = JSON.parse(JSON.stringify(info));
            this.formValidate = JSON.parse(JSON.stringify(info));
            // //判断此虚拟机是什么系统类型
            // let systemType;
            // try{
            //  systemType = await this.getSystemType(info.vmId);
            // }catch (e) {
            //   this.$Message.error(e.message)
            // }
            // if(systemType==='windows'){
            //   if(info.targetTempInfos[0].info.endsWith('html')){
            //     this.path=info.targetTempInfos[0].info;
            //   }else{
            //     this.path=`${info.targetTempInfos[0].info}/html`;
            //   }
            // }else{
            //   this.path=info.targetTempInfos[0].info;
            // }
          // this.path = systemType === 'windows' ? `${info.targetTempInfos[0].info.endsWith('html')}`?`${info.targetTempInfos[0].info}`:`${info.targetTempInfos[0].info}/html` : `${info.targetTempInfos[0].info}`
            this.path = info.targetTempInfos.length > 0 ? info.targetTempInfos[0].info : '';
            this.getAllVmlist();
//  			this.formValidate.path = info.targetTempInfos[0].info;
//  			this.getAllVmlist().then(()=>{
////  				this.formValidate = JSON.parse(JSON.stringify(info));
//  				this.path = info.targetTempInfos[0].info;
//  			});
            if (info.externalPort || info.externalIp) {
              this.access = "2";
            } else {
              this.access = "1";
            }
          }
        },
      addTargetTeam(){
        console.log(2222222);
        let params = JSON.parse(JSON.stringify(this.formValidate));
        if(this.path){  //如果有路径，添加团队临时信息
          params.targetTempInfos = [
            {
              "id": "",
              "info": this.path,
              "targetId": "",
              "type": 1  //flag路径
            }
        ]
        }
        if(this.access == "1"&&this.hlConfig!=2){
          params.externalPort = '';
            params.externalIp = '';
        }else if(this.access == "2"&&this.hlConfig!=2){
          params.port = '';
        }
        if(params.teamId){
          let group =  this.accessGroupList.filter(group => group.id == params.teamId)[0];
          params.teamName = group.name;
        }
        // if(this.hlConfig==2&&params.teamId!=''){
        //     params.user=this.vmUserName
        //     params.password=this.vmPassword
        // }
        if(this.hlConfig==2){
          delete params.score
          delete params.visibility
          delete params.externalPort
        }else{
          delete params.user
          delete params.password
          delete params.ip
        }
        addTargetTeam(params).then(data => {
          if(data.code==1){
                    this.queryTargetTeamInfo.pageIndex = 1
            this.getTargetTeamList();
            this.$Message.info('操作成功');
            this.targetModal.show = false;
          }else{
            this.cancelLoading('targetModal');
          }
          this.handleReset('formValidate');
        }).catch(error => {
          this.cancelLoading('targetModal');
        })
      },
      modifyTargetTeam(){
        let params = JSON.parse(JSON.stringify(this.formValidate));
        let id = '';
        if(this.formValidate.targetTempInfos.filter(temp => temp.type == 1).length > 0){
          id = this.formValidate.targetTempInfos[0].id
        }
        if(this.path){ //如果有路径，添加团队临时信息
          params.targetTempInfos = [
            {
              "id": id,
              "info": this.path,
              "targetId":params.id,
              "type": 1 //flag路径
            }
        ]
      }
        if(this.access == "1"&&this.hlConfig!=2){
          params.externalPort = '';
            params.externalIp = '';
        }else if(this.access == "2"&&this.hlConfig!=2){
          params.port = '';
        }
         if(params.teamId){
          let group =  this.accessGroupList.filter(group => group.id == params.teamId)[0];
          params.teamName = group.name;
        }
        modifyTargetTeam(params).then(data => {
          if(data.code==1){
            this.getTargetTeamList();
            this.$Message.info('操作成功');
            this.handleReset('formValidate');
            this.targetModal.show = false;
          }else{
            this.cancelLoading('targetModal');
          }
        }).catch(error => {
          this.cancelLoading('targetModal');
        })
      },
      saveTargetTeam(){
        this.$refs['formValidate'].validate((valid) => {
              if (valid) {
                if(this.targetModal.type == 1){
                  this.addTargetTeam();
                }else{
                  this.modifyTargetTeam();
                }
              }else{
                this.cancelLoading('targetModal');
                console.log(1231231);
              }
          })
      },
      getTargetTeamList(){
        getTargetTeamList(this.queryTargetTeamInfo).then(data => {
          if(data.code==1){
            this.targetTeamData = data.data.items || data.data;
            this.targetTeamTotal = data.data.total;
            if(this.step == 'pre'){
              if(this.targetTeamTotal > 0){
                this.$emit('setHasTarget',true);
              }else{
                this.$emit('setHasTarget',false);
              }
            }
          }else{
            if(this.step == 'pre'){
              this.$emit('setHasTarget',false);
            }
          }
        }).catch(error => {
          if(this.step == 'pre'){
            this.$emit('setHasTarget',false);
          }
        })
      },
      getAllUsedVm() {
        getTargetTeamList({
          pageIndex:1,
          pageSize:2147483646,
          sceneId:this.$route.query.id,
          projectId:this.$route.query.prjid
        }).then(({ code, message, data = {} }) => {
          if (code !== 1) {
            this.$Message.warning(message)
            return
          }
          this.usedVmList = (data.items && data.items.map(item => item.vmId)) || []
        }).catch(() => {
          this.$Message.error('查询已使用的虚拟机列表异常')
        })
      },
      delTargetTeam(id){
        delTargetTeam(id).then(data => {
          if(data.code==1){
                  // 删除后展示当前页，当前页没有数据展示前一页
                  this.queryTargetTeamInfo.pageIndex = (this.targetTeamData.length == 1 && this.queryTargetTeamInfo.pageIndex > 1) ?
                          this.queryTargetTeamInfo.pageIndex - 1 : this.queryTargetTeamInfo.pageIndex;
            this.getTargetTeamList();
          }else{

          }
        })
      },
      cancelLoading(name){
        this[name].loading = false;
          setTimeout(() => {
            this[name].loading = true;
          })
      },
      // typeFilter(val){
      //   let str = '';
      //   switch (val) {
      //     case 0:str = 'Flag';break;
      //     case 1:str = '多个虚拟机Flag相同';break;
      //     case 2:str = '多个虚拟机Flag不同';break;
      //     case 3:str = '文档';break
      //     default:break;
      //   }
      //   return str;
      // },
      typeFilter(val){
        let str = '';
        switch (val) {
          case 0:str = '私有';break;
          case 2:str = '公共';break;
          case 3:str = '隐藏';break
          default:break;
        }
        return str;
      },
      statusFilter(val){
        let str = '';
        switch (val) {
          case 1:str = '正常/防护成功';break;
          case 2:str = '被攻破';break;
          case 3:str = '服务异常';break;
          case 4:str = '被攻破+服务异常';break
          default:break;
        }
        return str;
      },
      getAllVmlist(){
        return new Promise((resolve,reject)=>{
          let params = {
          pageIndex:1,
          pageSize:10000,
          sortBy:'name',
          order:'asc',
          vmTypes:['TARGET','TEST']
        }
        if(this.type==0&&this.hlConfig==2){
          delete params.vmTypes
        }
//		        if(this.question){
//		        	params.imageId = this.question.imageId;
//		        }
            if(this.formValidate.teamId&&this.hlConfig!=2){
              let group =  this.accessGroupList.filter(group => group.id == this.formValidate.teamId)[0];
              params.partyId = group.partyId;
            }
            queryDeployedVms(this.routeParams.prjid,params).then(data => {
//				queryVmWithParty(this.routeParams.prjid,params).then(data => {
          if(data.code == 1){
            this.vmlists = data.data.items || data.data;
            //this.getVmIp(this.formValidate.vmId);
//						if(this.vmlists.length > 0){
//							let server = this.vmlists.filter(vm => vm.id == this.formValidate.vmId)[0];
//		    		        if(server){
//		    		        	this.getFlagServerList(server.address[0].ipv4);
//		    		        }
//						}
          }
        })
        this.getAllUsedVm();
        })
      },
      getAccessGroupList(){
      if(!this.routeParams.id){
        return;
      }
      let params = {
        pageIndex:1,
        pageSize:2147483647,
        testId:this.routeParams.id
      };
      this.selectGroupList = [];
//			this.getPartyList();
      getaccessgrouplist(params).then(data => {
        if(data.code == 1){
          this.accessGroupList = data.data.items;
        }else if(data.code == -2) {
          this.accessGroupList = [];
        }else{
          this.$Message.warning(data.message);
        }
        //this.getUserTaskList();
      })
    },
      getTargetSize(size){
        this.queryTargetTeamInfo.pageSize = size;
        this.getTargetTeamList()
      },
      getTargetPage(page){
        this.queryTargetTeamInfo.pageIndex = page;
        this.getTargetTeamList()
      },
      changeTeamGroup(val){
        this.formValidate.vmId = '';
        this.formValidate.name = '';
        this.formValidate.description = '';
        this.formValidate.port = '';
        this.path = '';
        if(!val){
          return
        }
        this.getAllVmlist();
      },
//	    setTeamGroup(val){
//	    	this.getAllVmlist();
//	    },
      handleReset (name) {
        this.$refs[name].resetFields();
        //   this.addTarget = false;
          this.initData();
        //   this.$refs [name].fields.forEach(function (e) {
        //     if (e.fieldValue != undefined && e.fieldValue!='') {
        //         e.resetField()
        //     }
        //  })
      },
      queryCtfQuestionList(id){//查询ctf题列表-不分页--需要环境
        return new Promise((resolve,reject) => {
            // let obj = {
            //   pageIndex:1,
            //   pageSize:1,
            //   chaId:id
            // };
            getQuestionDetail(id).then(data => {
              if(data.code == 1){
                resolve(data.data);
              }else{
                reject()
              }
            }).catch(error => {
              reject()
            })
          })
      },
      queryTargetList(id){
        return new Promise((resolve,reject) => {
          let params = {
            page:1,
            rows:1,
            targetId:id
          }
          queryTargetList(params).then(data =>{
            if(data.code == 1){
              resolve(data.attribute.data[0])
            }else{
              reject()
            }
          }).catch(error => {
            reject()
          })
        })
      },
      getQuesOrTargetDetail(server){
        return new Promise(async resolve => {
          if(server.vmType == 'TARGET'){
            let targetDetail = await this.queryTargetList(server.useId) || {};
            this.formValidate.name = targetDetail.targetName || '';
            this.formValidate.description = targetDetail.description || '';
            this.formValidate.port = targetDetail.openPort || '';
            this.originalPath = targetDetail.flagPath || '';
          }else if(server.vmType == 'TEST'){
            let quesDetail = await this.queryCtfQuestionList(server.useId) || {};
            this.formValidate.name = quesDetail.name || '';
            this.formValidate.description = quesDetail.description || '';
            this.formValidate.port = quesDetail.port || '';
            this.originalPath = quesDetail.flagPath || '';
          }
          resolve()
        })
      },
      changeType(){
        this.formValidate.description=''
        this.formValidate.externalIp=''
        this.formValidate.externalPort=''
        this.formValidate.name=''
        this.formValidate.password=''
        this.formValidate.user=''
        this.formValidate.port=''
        this.formValidate.ip=''
        this.formValidate.teamId=''
        this.formValidate.questionId=''
        this.formValidate.score=1
        this.formValidate.teamName=''
        this.formValidate.visibility=0
        this.formValidate.vmId=''
        this.formValidate.path=''
        this.formValidate.sequence=''
        this.$refs.formValidate.fields.forEach((e) => {
            if (e.prop == 'name'||e.prop == 'description'||e.prop == 'port'||e.prop == 'vmId'||e.prop == 'user'||e.prop == 'IP') {
              e.resetField()
            }
          })

        console.log(this.formValidate.type,111111111111111);
      },
      changeVm(id){

        if(id){
          this.getVmIp(id);
        }
      },
      async getVmIp(id){
        if(id){
          let server = this.vmlists.filter(vm => vm.id == id)[0];
          await this.getQuesOrTargetDetail(server);
          this.getFlagServerList(server.addresses[0].ips[0].ipAddress,server);
        }
      },
      // 存在Flag服务器时，需要改写path的值，如果无法查询到相关数据，path设置为题目原本的路径
      getFlagServerList(ip,server){
        let curIp = ip.split('.').slice(0,3).join('.');
        let params = {
          page:1,
          pageSize:1000,
          projectId:this.$route.query.prjid,
          ip:curIp
        }
        getFlagServerList(params).then(data => {
          if(data.code == 1){
            let path;
            if(data.data.list.length > 0 && data.data.list[0].addresses.length > 0){
              if(server.sysType==='windows'){
                path = data.data.list[0].addresses[0].applyFlagUrl+'/html';
              }else{
                path = data.data.list[0].addresses[0].applyFlagUrl;
              }
            }
            if(path){
              this.path = path;
            } else {
              this.path = this.originalPath
            }
          } else {
            this.path = this.originalPath
          }
        }).catch(() => {
          this.path = this.originalPath
        })
      },
      changeAccess(access){
//	    	if(access == "1" && this.targetModal.type == 2){
//	    		this.formValidate.externalPort = this.oldFormValidate.externalPort;
//    			this.formValidate.externalIp = this.oldFormValidate.externalIp;
//	    	}else if(access == "2" && this.targetModal.type == 2){
//	    		this.formValidate.port = this.oldFormValidate.port;
//	    	}
      },
  }
}
</script>

<style>
  .drillsTable .ivu-poptip-body {
    text-align: left!important;
  }
  .scenesHeader{
    margin-bottom: 16px;
  }
  .drillTables{
    min-height: 300px;
  }
  .drillsTable.ivu-table-wrapper{
    overflow: inherit;
  }
</style>
<style scoped>
  .Titles{
    background: #eeeeee;
    margin: 16px auto;
    padding: 10px 0;
  }
  .targetHeader{
    /*padding: 10px;*/
    margin:15px 0;
  }
</style>
